package vip.ifmm.lehouse.user.service.utils;

import org.omg.CORBA.TIMEOUT;
import vip.ifmm.lehouse.common.bo.SessionBo;
import vip.ifmm.lehouse.common.model.User;
import vip.ifmm.lehouse.common.util.Md5Util;

import java.util.Map;

/**
 * @author Red
 * email: 1318944013@qq.com
 * date: 2019/6/16 20:06
 */
@SuppressWarnings("all")
public class SessionUtil {

    private static final long REDIS_VALUE_TIME_OUT = 3600;

    private static final String SESSION_TOKEN_KEY = "session-token:";

    /**
     * 获得token方法: userId + md5加密
     *
     * @param user user对象
     * @return token
     */
    public static String getToken(User user) {
        return SESSION_TOKEN_KEY + Md5Util.DoubleMD5(user.getUserId().toString()).substring(0, 10);
    }

    /**
     * 将session放入redis
     *
     * @param session session对象
     * @param timeout 过期时间
     * @return token
     */
    public static String putSession(SessionBo session, long timeout) {
        // 生成token
        String token = getToken(session.getUser());
        if (timeout > 0) {
            // 将session放入redis中, 过期时间一天
            RedisUtil.set(token, session, timeout);
        } else {
            RedisUtil.set(token, session, REDIS_VALUE_TIME_OUT);
        }
        return token;
    }

    public static String putSession(SessionBo session) {
        return putSession(session, -1);
    }

    /**
     * 将Use和Map封装成session对象
     *
     * @param user user对象
     * @param data 用map保存数据
     * @return SessionBo
     */
    public static SessionBo getSessionBo(User user, Map<String, Object> data) {
        return SessionBo.builder().user(user).data(data).build();
    }

    public static SessionBo getSessionBo(User user) {
        return getSessionBo(user, null);
    }
}
